package com.zjq.springsocial.renren.android.ui.auth;

import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.DuplicateConnectionException;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.GrantType;
import org.springframework.social.oauth2.OAuth2Parameters;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.zjq.springsocial.renren.android.R;
import com.zjq.springsocial.renren.android.RenrenAbstractAsyncActivity;
import com.zjq.springsocial.renren.android.ui.RenrenIndexActivity;
import com.zjq.springsocial.renren.api.Renren;
import com.zjq.springsocial.renren.connect.RenrenConnectionFactory;

/**
 * <P>
 * 用户oauth2.0认证授权activity
 * </P>
 * 
 * @author zhongjingquan
 * 
 * @version 0.0.1-SNAPSHOT 2013-7-19下午2:47:23
 */
public class RenrenAuthzActivity extends RenrenAbstractAsyncActivity{

	private static final String TAG = RenrenAuthzActivity.class.getSimpleName();
	// 连接资源对象
	private ConnectionRepository connectionRepository;
	// 人人网连接工厂对象
	private RenrenConnectionFactory renrenConnectionFactory;
	
	private WebView webView;
	
	private RenrenAuthzActivity activity;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_PROGRESS);
		getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.webView = new WebView(this);
		setContentView(webView);
		this.activity = this;
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new RenrenOAuthWebViewClient());
		this.connectionRepository = getApplicationContext().getConnectionRepository();
		this.renrenConnectionFactory = getApplicationContext().getRenrenConnectionFactory();
	}
	
	@Override
	public void onStart() {
		super.onStart();

		// display the Facebook authorization page
		webView.loadUrl(getAuthorizeUrl());
	}

	// ***************************************
	// Private methods
	// ***************************************
	private String getAuthorizeUrl() {
		String redirectUri = getString(R.string.renren_oauth_callback_url);
		String scope = getString(R.string.renren_scope);
		OAuth2Parameters params = new OAuth2Parameters();
		params.setRedirectUri(redirectUri);
		params.setScope(scope);
		params.add("display", "touch");
		return this.renrenConnectionFactory.getOAuthOperations().buildAuthorizeUrl(GrantType.IMPLICIT_GRANT, params);
	}

	private void displayRenrenOptions() {
		Intent intent = new Intent();
		intent.setClass(this,RenrenIndexActivity.class);
		startActivity(intent);
		finish();
	}
	
	//人人网oauth客户端
	private class RenrenOAuthWebViewClient extends WebViewClient{
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Uri uri = Uri.parse(url);
			Log.d(TAG, url);

			/*
			 * https://graph.renren.com/oauth/token
			 *	    "access_token": "10000|5.a6b7dbd428f731035f771b8d15063f61.86400.1292922000-222209506",
			 *	    "expires_in": 87063,
			 *	    "refresh_token": "10000|0.385d55f8615fdfd9edb7c4b5ebdc3e39-222209506",
			 *	    "scope": "read_user_album read_user_feed"
			 */
			String uriFragment = uri.getFragment();

			// confirm we have the fragment, and it has an access_token parameter
			if (uriFragment != null && uriFragment.startsWith("access_token=")) {

				/*
				 * The fragment also contains an "expires_in" parameter. In this
				 * example we requested the offline_access permission, which
				 * basically means the access will not expire, so we're ignoring
				 * it here
				 */
				try {
					// split to get the two different parameters
					String[] params = uriFragment.split("&");

					// split to get the access token parameter and value
					String[] accessTokenParam = params[0].split("=");

					// get the access token value
					String accessToken = accessTokenParam[1];

					// create the connection and persist it to the repository
					AccessGrant accessGrant = new AccessGrant(accessToken);
					Connection<Renren> connection = renrenConnectionFactory.createConnection(accessGrant);

					try {
						connectionRepository.addConnection(connection);
					} catch (DuplicateConnectionException e) {
						e.printStackTrace();
						// connection already exists in repository!
					}
				} catch (Exception e) {
					// don't do anything if the parameters are not what is expected
					e.printStackTrace();
				}

				displayRenrenOptions();
			}

			/*
			 * if there was an error with the oauth process, return the error description
			 * 
			 * The error query string will look like this:
			 * 
			 * ?error_reason=user_denied&error=access_denied&error_description=The +user+denied+your+request
			 */
			if (uri.getQueryParameter("error") != null) {
				CharSequence errorReason = uri.getQueryParameter("error_description").replace("+", " ");
				Toast.makeText(getApplicationContext(), errorReason, Toast.LENGTH_LONG).show();
				displayRenrenOptions();
			}
		}
	}
}
